﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using AutoMapper;
using System.Data;
using RH.Web.ViewModels.UtilityModels;


namespace RH.Web.Areas.Private.Controllers
{
    [Authorize(Roles = "Company Admin,Company User")]
    public class UserController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		#region Constructors
		public UserController()
		{
		}

		public UserController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View();
        }
		/// <summary>
        /// Gets a Contact from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0)
        {
            Contact entity = id == 0 ? new Contact() : _Context.Contacts.FirstOrDefault(P => P.ID == id);
            if (id == 0)
            {
                entity.IsActive = true;
                entity.CompanyID = LoggedInUser.Company.ID;
            }

            ContactViewModel viewModel = Mapper.Map<Contact, ContactViewModel>(entity);             
            return View(viewModel);
        }

        public ActionResult CreateUser(int id = 0)
        {
            Contact entity = id == 0 ? new Contact() : _Context.Contacts.FirstOrDefault(P => P.ID == id && P.CompanyID == LoggedInUser.Company.ID);
            if (entity == null)
            {
                return RedirectToAction("List");
            }
            else
            {
                //if (id == 0)
                //{
                entity.IsActive = true;
                entity.CompanyID = LoggedInUser.Company.ID;
                //}

                //RegisterModel viewModel = Mapper.Map<Register, RegisterModel>(entity);
                ViewBag.ContactEmail = "CreateUser@Yahoo.com";
                return View();
            }

            //Contact entity = id == 0 ? new Contact() : _Context.Contacts.FirstOrDefault(P => P.ID == id);
            //if (id == 0)
            //{
            //    entity.IsActive = true;
            //    entity.CompanyID = LoggedInUser.Company.ID;
            //}

            //ContactViewModel viewModel = Mapper.Map<Contact, ContactViewModel>(entity);
            //return View(viewModel);
        }

        //[HttpPost]
        //public ActionResult CreateUser(RegisterModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (_Context.IsDuplicateEmail(model.Email))
        //            ModelState.AddModelError("", "The User ID address is already taken. Please choose another.");
        //        else
        //        {
        //            User user = new User();
        //            user.UserName = model.Email;
        //            user.Password = model.Password;
        //            user.GroupID = ConfigReader.UserGroupIDOfSiteUser;
        //            user.IsActive = true;

        //            _Context.AddToUsers(user);
        //            _Context.SaveChanges();
        //            //// Attempt to register the user
        //            //MembershipCreateStatus createStatus;
        //            //Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

        //            //if (createStatus == MembershipCreateStatus.Success)
        //            //{
        //            //    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
        //            //    return RedirectToAction("Index", "Home");
        //            //}
        //            //else
        //            //{
        //            //    ModelState.AddModelError("", ErrorCodeToString(createStatus));
        //            //}

        //            return RedirectToAction("List");
        //            //return RedirectToAction("Register", new { msg = "True" });
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return View(model);
        //}

		/// <summary>
        /// Saves Contact Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult Edit(ContactViewModel viewModel)
        {
			if (!ModelState.IsValid)
                return View(viewModel);

			Contact entity = null; 
			if (viewModel.ID == 0)
            {
                entity = new Contact();
                _Context.AddToContacts(entity);
            }
            else
                entity = _Context.Contacts.FirstOrDefault(P => P.ID == viewModel.ID);

            entity = Mapper.Map<ContactViewModel, Contact>(viewModel, entity);
            //if (entity.ReligionID.GetValueOrDefault() == 0)
            //    entity.ReligionID = null;            
            _Context.SaveChanges();
            return RedirectToAction("List");        
        }		
		#endregion Action Methods

        public ActionResult List()
        {
            UtilityDAO dao = new UtilityDAO();
            RH.Domain.DbParameter[] parameters = new[]{
                new RH.Domain.DbParameter("@CompanyID", LoggedInUser.Company.ID)
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_USERS_BY_COMPANY, parameters, true);
            //DataTable dt = BuildDataTable();
            //DateTime start = DateTime.Now;
            ListConfig config = RH.Web.ViewModels.UtilityModels.ListConfigBuilder.Build(
                @"Basic Info{ ID | Name | UserName  }, 
                Personal Info{Personal Email | Office Email | Cell Phone}",
                ds.Tables[0], "");

            
            ViewBag.ListConfig = config;
            return View();
        }

        //[HttpPost]
        //public int CreateUser(string userName, string password, int contactId, string saveEdit)
        //{
        //    if (saveEdit.Trim() == "")
        //    {
        //        if (!_Context.IsDuplicateUserName(userName, 0))
        //        {
        //            User user;

        //            user = new User();

        //            user.UserName = userName;
        //            user.Password = password;
        //            user.GroupID = ConfigReader.UserGroupIDOfSiteUser;
        //            user.IsActive = true;

        //            _Context.AddToUsers(user);
        //            _Context.SaveChanges();

        //            UserContact uc = new UserContact();
        //            uc.UserID = user.ID;
        //            uc.ContactID = contactId;

        //            _Context.AddToUserContacts(uc);
        //            _Context.SaveChanges();

        //            return 1;
        //        }
        //    }
        //    else
        //    {
        //        UserContact uc = _Context.UserContacts.FirstOrDefault(P => P.ContactID == contactId);


        //        if (!_Context.IsDuplicateUserName(userName, uc.UserID))
        //        {
        //            User user = _Context.Users.FirstOrDefault(Q => Q.ID == uc.UserID); 

        //            user.UserName = userName;
        //            user.Password = password;
        //            user.GroupID = ConfigReader.UserGroupIDOfSiteUser;
        //            user.IsActive = true;

        //            _Context.SaveChanges();

        //            return 1;
        //        }
        //    }

            
        //    return -1;
        //}
		
		#region Helper Methods
        public ActionResult Gender()
        {           

            return Gender();
        }
        #endregion			
    }
}
